//显示树状图
$(function () {
    //setting对象中包括  zTree的设置属性
    var setting ={
        view:{
            "addDiyDom":showMyIcon,
            "addHoverDom": addHoverDom,
            "removeHoverDom": removeHoverDom
        },
        data:{
            key:{
                url:"notExistsProperty"
            }
        }
    };
    $.ajax({
        url:"/tag/get/whole/tree",
        type:"post",
        dataType:"json",
        success:function (ajaxResult) {
            var result=ajaxResult.result;
            if(result=="SUCCESS"){
                var zNodes=ajaxResult.data;
                $.fn.zTree.init($("#treeDemo"),setting,zNodes);
            }else{
                layer.msg("加载菜单数据失败！原因是："+response.message);
            }
        }

    })
})

//显示图标 修改class
function showMyIcon(treeId,treeNode) {
    console.log(treeId);
    console.log(treeNode);
    //获取当前节点的id
    var currentNodeId=treeNode.tId;
    var  newClass=treeNode.icon;
    var targetSpanId=currentNodeId+"_ico";
    $("#"+targetSpanId).removeClass().addClass(newClass).css("background","");
}

//生成按钮组
function generateBtnGrp(treeNode) {
    //获取当前节点的id(li的id)
    var tid=treeNode.tId;
    //组装按钮组所在span的Id
    var btnGrpSpanId=tid+"_btnGrp";
    //生成span标签jquery对应的对象
    var $span=$("<span id='"+btnGrpSpanId+"'><span/>")
    //获取当前节点在数据库中的id
    var tagId=treeNode.id;
    //获取当前节点的level
    var level=treeNode.level;

    // 声明三种按钮
    var addBtn = "<a onclick='showAddModal(this)' id='"+tagId+"' class='btn btn-info dropdown-toggle btn-xs' style='margin-left:10px;padding-top:0px;' title='添加子节点'>&nbsp;&nbsp;<i class='fa fa-fw fa-plus rbg'></i></a>";
    var editBtn = "<a onclick='showEditModal(this)' id='"+tagId+"' class='btn btn-info dropdown-toggle btn-xs' style='margin-left:10px;padding-top:0px;' title='编辑节点'>&nbsp;&nbsp;<i class='fa fa-fw fa-edit rbg'></i></a>";
    var removeBtn = "<a onclick='showConfirmModal(this)' id='"+tagId+"' class='btn btn-info dropdown-toggle btn-xs' style='margin-left:10px;padding-top:0px;' title='删除节点'>&nbsp;&nbsp;<i class='fa fa-fw fa-times rbg'></i></a>";

    // 根据level进行判断
    if(level==1){
        $span.append(addBtn);
    }else if(level==2){
        if(treeNode.children.length>0){
            $span.append(addBtn+" "+editBtn);
        }else{
            $span.append(addBtn+" "+editBtn+" "+removeBtn);
        }
    }else{
        $span.append(editBtn+" "+removeBtn);
    }
    return $span;
}

//鼠标悬浮调用此方法
function addHoverDom(treeId, treeNode){
    var btnGrpSpanId = treeNode.tId + "_btnGrp";

    var btnGrpSpanLength = $("#"+btnGrpSpanId).length;

    if(btnGrpSpanLength > 0) {
        return ;
    }
    //获取按钮组
    var btnGrpSpan=generateBtnGrp(treeNode);
    //先定位到a标签
    var anchorId=treeNode.tId+"_a";
    //在a标签后面追加按钮组
    $("#"+anchorId).append(btnGrpSpan);
}
////鼠标移出节点时调用此方法
function removeHoverDom(treeId, treeNode) {
    // 组装按钮组所在的span标签的id
    var btnGrpSpanId=treeNode.tId+"_btnGrp";
//删除对应的元素
    $("#"+btnGrpSpanId).remove();
}